/*
	Cells are individual blocks in the game. They are of different types -
	#(35) - Wall
	@(64) - Is where 'we' are
	+(43) - Is where 'we' are on an empty slot
	.(46) - Is an empty sink
	*(42) - is a filled sink
	$(36) - is an out of position block
	 (32) - a blank cell, we put a space in there, is a normal cell
*/
var cellTypes = [35,64,43,46,42,36,32];

// A level is one puzzle; it is an array of cells
// An episode is an array of levels
// game is a hash of episodenames-episodes
var game = {};
var moveList = [];
var moveListIndex = 0;
function isValidCellType(code)
{
	for(var i = 0;i < cellTypes.length;i++)
		if(code == cellTypes[i])
			return 1;
	return 0;
}

function isNewLevel(line)
{
	var levelNumber = -1;
	for(var i = 0;line != undefined && i < line.length;i++)
	{
		// Check for ';'
		if(line.charCodeAt(i) == 59)
		{
			levelNumber = line.substr(i + 1);
			levelNumber = parseInt(levelNumber);
			break;
		}
	}
	return levelNumber;
}

function parseLevel(lines)
{
	var row = 0;
	var column = 0;
	var level = [];
	var levelNumber;
	
	while(lines.length)
	{
		var l = lines.shift();
		levelNumber = isNewLevel(l);
		if(levelNumber != -1)
			break;
	}
	
	var maxWidth = 0;
	while(row < lines.length && isNewLevel(lines[row]) == -1)
	{					
		var line = [];
		var flag = 1;
		if(maxWidth < lines[row].length - 1)
			maxWidth = lines[row].length - 1;
		for(column = 0;column < lines[row].length;column++)
		{
			var char = lines[row].substring(column,column + 1);
			var code = char.charCodeAt(0);
			if(code == 13)
				continue;
			if(isValidCellType(code))
				line[column] = code;
			else
			{
				flag = 0;
				break;
			}
		}
		if(flag && line.length)
		{
			level[row] = line;
			row++;
		}
		else
		{
			lines.splice(row,1);
		}
	}
	
	for(row = 0;row < level.length;row++)
	{
		for(column = 0;column < level[row].length;column++)
		{
		}
		while(column < maxWidth)
			level[row][column++] = 30;
	}
	
	lines.splice(0,row);
	return [levelNumber,level];
}

function parseEpisode(name,text)
{
	var lines = text.split('\n');
	var episode = [];
	while(lines.length)
	{
		var newEp = parseLevel(lines);
		if(newEp[0] == -1)
			continue;
		episode[episode.length] = newEp[1];
	}
	game[name] = episode;
}

function getEpisode(episode)
{
	var file = new XMLHttpRequest();
	file.open("GET",episode,false);
	file.send();
	var text = file.responseText;
	parseEpisode(episode,text);
}
